// 更新地址
const cloud = require('wx-server-sdk')

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})

const db = cloud.database()

exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  const { addressId, receiver, phoneNumber, region, detail, isDefault } = event
  
  // 直接使用openid作为用户标识
  if (!wxContext.OPENID) {
    return {
      success: false,
      message: '用户未登录'
    }
  }
  
  const userOpenid = wxContext.OPENID

  // 参数验证
  if (!addressId) {
    return {
      success: false,
      message: '地址ID不能为空'
    }
  }

  if (!receiver || !phoneNumber || !region || !detail) {
    return {
      success: false,
      message: '缺少必要参数'
    }
  }

  // 验证手机号格式
  const phoneRegex = /^1[3-9]\d{9}$/
  if (!phoneRegex.test(phoneNumber)) {
    return {
      success: false,
      message: '手机号格式不正确'
    }
  }

  // 验证省市区
  if (!Array.isArray(region) || region.length !== 3 || !region[0] || !region[1] || !region[2]) {
    return {
      success: false,
      message: '请选择完整的省市区'
    }
  }

  try {
    // 先查询地址是否存在并验证所有权
    const addressResult = await db.collection('addresses')
      .doc(addressId)
      .get()

    if (!addressResult.data) {
      return {
        success: false,
        message: '地址不存在'
      }
    }

    if (addressResult.data.userId !== userOpenid) {
      return {
        success: false,
        message: '无权限修改此地址'
      }
    }

    const now = new Date()
    
    // 如果设置为默认地址，先将用户其他地址的默认状态设为false
    if (isDefault && !addressResult.data.isDefault) {
      await db.collection('addresses')
        .where({
          userId: userOpenid
        })
        .update({
          data: {
            isDefault: false,
            updatedAt: now
          }
        })
    }

    // 更新地址信息
    await db.collection('addresses')
      .doc(addressId)
      .update({
        data: {
          receiver: receiver.trim(),
          phoneNumber: phoneNumber.trim(),
          region: region,
          detail: detail.trim(),
          isDefault: isDefault || false,
          updatedAt: now
        }
      })

    return {
      success: true,
      message: '地址修改成功'
    }
  } catch (error) {
    console.error('更新地址失败:', error)
    return {
      success: false,
      message: '更新地址失败',
      error: error.message
    }
  }
}